<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>剪映影音分离和音频切割工具</title>
    <style>
        :root {
            --primary-color: #3498db;
            --primary-hover: #2980b9;
            --secondary-color: #e74c3c;
            --secondary-hover: #c0392b;
            --success-color: #2ecc71;
            --warning-color: #f39c12;
            --text-color: #333;
            --light-bg: #f5f5f5;
            --border-color: #ddd;
        }
        
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            line-height: 1.6;
            color: var(--text-color);
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            padding: 20px;
            min-height: 100vh;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            padding: 20px;
            overflow: hidden;
        }
        
        .header {
            text-align: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid var(--border-color);
        }
        
        h1 {
            color: var(--primary-color);
            font-size: 1.8rem;
            margin-bottom: 10px;
        }
        
        .tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 1px solid var(--border-color);
        }
        
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border: none;
            background: none;
            font-size: 1rem;
            font-weight: bold;
            color: var(--text-color);
            transition: all 0.3s;
            border-bottom: 2px solid transparent;
        }
        
        .tab.active {
            color: var(--primary-color);
            border-bottom: 2px solid var(--primary-color);
        }
        
        .tab-content {
            display: none;
            padding: 15px 0;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        .file-input {
            display: flex;
            align-items: center;
            padding: 10px 0;
        }
        
        .file-input input[type="text"] {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            font-size: 0.9rem;
            margin-right: 10px;
            background-color: var(--light-bg);
            cursor: default;
        }
        
        .radio-group {
            display: flex;
            gap: 15px;
            margin: 10px 0;
        }
        
        .radio-option {
            display: flex;
            align-items: center;
        }
        
        .radio-option input[type="radio"] {
            margin-right: 5px;
        }
        
        input[type="number"] {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            font-size: 1rem;
        }
        
        button {
            background-color: var(--primary-color);
            color: white;
            border: none;
            padding: 10px 20px;
            font-size: 1rem;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        button:hover {
            background-color: var(--primary-hover);
        }
        
        button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        
        .btn-secondary {
            background-color: var(--secondary-color);
        }
        
        .btn-secondary:hover {
            background-color: var(--secondary-hover);
        }
        
        .progress-container {
            margin-top: 20px;
            display: none;
        }
        
        .progress-bar {
            height: 20px;
            background-color: var(--light-bg);
            border-radius: 10px;
            overflow: hidden;
            margin-bottom: 10px;
        }
        
        .progress {
            height: 100%;
            background-color: var(--primary-color);
            width: 0;
            transition: width 0.3s;
        }
        
        .message {
            padding: 10px;
            margin-top: 15px;
            border-radius: 4px;
            display: none;
            word-break: break-word;
        }
        
        .message.success {
            background-color: rgba(46, 204, 113, 0.2);
            color: var(--success-color);
            border: 1px solid var(--success-color);
            display: block;
        }
        
        .message.error {
            background-color: rgba(231, 76, 60, 0.2);
            color: var(--secondary-color);
            border: 1px solid var(--secondary-color);
            display: block;
        }
        
        .message.warning {
            background-color: rgba(243, 156, 18, 0.2);
            color: var(--warning-color);
            border: 1px solid var(--warning-color);
            display: block;
        }
        
        .output-list {
            margin-top: 15px;
            max-height: 150px;
            overflow-y: auto;
            background-color: var(--light-bg);
            padding: 10px;
            border-radius: 4px;
            border: 1px solid var(--border-color);
        }
        
        .output-item {
            margin-bottom: 5px;
            padding: 5px;
            border-bottom: 1px solid var(--border-color);
            word-break: break-all;
        }
        
        .footer {
            margin-top: 20px;
            text-align: center;
            font-size: 0.8rem;
            color: #888;
            padding-top: 15px;
            border-top: 1px solid var(--border-color);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>剪映影音分离和音频切割工具</h1>
            <p>简单实用的媒体处理工具</p>
        </div>
        
        <div class="tabs">
            <button class="tab active" data-tab="video-separation">影音分离</button>
            <button class="tab" data-tab="audio-split">音频切割</button>
        </div>
        
        <div id="video-separation" class="tab-content active">
            <div class="form-group">
                <label>选择视频文件:</label>
                <div class="file-input" id="video-file-input-area">
                    <input type="text" id="video-file-path" placeholder="点击浏览选择视频文件" readonly>
                    <button id="browse-video-btn">浏览</button>
                </div>
            </div>
            
            <div class="form-group">
                <label>分离模式:</label>
                <div class="radio-group">
                    <div class="radio-option">
                        <input type="radio" name="separation-mode" id="mode-audio" value="audio" checked>
                        <label for="mode-audio">仅提取音频</label>
                    </div>
                    <div class="radio-option">
                        <input type="radio" name="separation-mode" id="mode-video" value="video">
                        <label for="mode-video">仅提取视频(无声)</label>
                    </div>
                    <div class="radio-option">
                        <input type="radio" name="separation-mode" id="mode-both" value="both">
                        <label for="mode-both">提取音频和视频</label>
                    </div>
                </div>
            </div>
            
            <button id="start-separation-btn" disabled>开始处理</button>
        </div>
        
        <div id="audio-split" class="tab-content">
            <div class="form-group">
                <label>选择音频文件:</label>
                <div class="file-input" id="audio-file-input-area">
                    <input type="text" id="audio-file-path" placeholder="点击浏览选择音频文件" readonly>
                    <button id="browse-audio-btn">浏览</button>
                </div>
            </div>
            
            <div class="form-group">
                <label>切割方式:</label>
                <div class="radio-group">
                    <div class="radio-option">
                        <input type="radio" name="split-method" id="method-time" value="time" checked>
                        <label for="method-time">按时间切割</label>
                    </div>
                    <div class="radio-option">
                        <input type="radio" name="split-method" id="method-segments" value="segments">
                        <label for="method-segments">按段数切割</label>
                    </div>
                </div>
            </div>
            
            <div id="time-input" class="form-group">
                <label>每段时长(分):</label>
                <input type="number" id="segment-time" min="1" value="15">
            </div>
            
            <div id="segments-input" class="form-group" style="display: none;">
                <label>切割段数:</label>
                <input type="number" id="segment-count" min="2" value="3">
            </div>
            
            <button id="start-split-btn" disabled>开始处理</button>
        </div>
        
        <div class="progress-container" id="progress-container">
            <div class="progress-bar">
                <div class="progress" id="progress-bar"></div>
            </div>
            <p id="progress-text">处理中...</p>
        </div>
        
        <div class="message" id="message"></div>
        
        <div class="output-list" id="output-list" style="display: none;">
            <h3>输出文件:</h3>
            <div id="output-items"></div>
        </div>
        
        
    </div>
    
    <script>
        // 将此函数暴露给window对象，以便Python可以调用
        window.frontend_handle_file_selection_result = function(status, filePath, fileName, originalFileType, message) {
            let targetInputId = null;
            let targetButtonId = null;

            if (originalFileType === 'video') {
                targetInputId = 'video-file-path';
                targetButtonId = 'start-separation-btn';
            } else if (originalFileType === 'audio') {
                targetInputId = 'audio-file-path';
                targetButtonId = 'start-split-btn';
            } else {
                showMessage('error', '内部错误：无法识别文件类型以更新UI。');
                return;
            }

            if (status === 'success') {
                const inputElement = document.getElementById(targetInputId);
                const buttonElement = document.getElementById(targetButtonId);
                if (inputElement) inputElement.value = filePath;
                if (buttonElement) buttonElement.disabled = false;
                showMessage('success', `已选择文件: ${fileName}`);
            } else if (status === 'cancelled') {
                showMessage('warning', message || '文件选择已取消。');
            } else { // error
                showMessage('error', `文件选择失败: ${message || '未知错误'}`);
            }
        };

        window.addEventListener('pywebviewready', function() {
            // 注意: Python端的API函数名现在是 api_is_ready, api_trigger_file_dialog 等
            pywebview.api.api_is_ready().then(response => {
                 // console.log("API api_is_ready response:", response) //保留注释以备将来调试
            }).catch(e => showMessage('error', 'API 初始化检查失败: ' + e));
            
            pywebview.api.api_check_ffmpeg().then(function(response) {
                if (response.status !== 'success') {
                    showMessage('error', 'FFmpeg检测失败: ' + response.message);
                }
            }).catch(e => showMessage('error', 'FFmpeg检测调用失败: ' + e));
            
            pywebview.api.api_get_version().then(function(data) {
                if (data && data.version) {
                    const versionSpan = document.getElementById('version');
                    if(versionSpan) versionSpan.textContent = data.version;
                }
            }).catch(e => showMessage('error', '获取版本号失败: ' + e));
        });
        
        // 切换标签页
        const tabs = document.querySelectorAll('.tab');
        const tabContents = document.querySelectorAll('.tab-content');
        
        tabs.forEach(tab => {
            tab.addEventListener('click', () => {
                const tabId = tab.getAttribute('data-tab');
                tabs.forEach(t => t.classList.remove('active'));
                tab.classList.add('active');
                tabContents.forEach(content => {
                    content.classList.remove('active');
                    if (content.id === tabId) content.classList.add('active');
                });
            });
        });

        document.getElementById('browse-video-btn').addEventListener('click', () => {
            // Python端会处理对话框，并通过 frontend_handle_file_selection_result 回调
            pywebview.api.api_trigger_file_dialog('video').catch(err => {
                showMessage('error', '请求视频文件选择对话框时发生脚本错误: ' + err);
            });
        });
        
        document.getElementById('browse-audio-btn').addEventListener('click', () => {
            // Python端会处理对话框，并通过 frontend_handle_file_selection_result 回调
            pywebview.api.api_trigger_file_dialog('audio').catch(err => {
                showMessage('error', '请求音频文件选择对话框时发生脚本错误: ' + err);
            });
        });
        
        // 切换音频切割方式的输入字段显示
        document.querySelectorAll('input[name="split-method"]').forEach(radio => {
            radio.addEventListener('change', () => {
                const timeInputDiv = document.getElementById('time-input');
                const segmentsInputDiv = document.getElementById('segments-input');
                if (radio.value === 'time') {
                    timeInputDiv.style.display = 'block';
                    segmentsInputDiv.style.display = 'none';
                } else {
                    timeInputDiv.style.display = 'none';
                    segmentsInputDiv.style.display = 'block';
                }
            });
        });
        
        // 开始视频分离
        document.getElementById('start-separation-btn').addEventListener('click', () => {
            const filePath = document.getElementById('video-file-path').value;
            const mode = document.querySelector('input[name="separation-mode"]:checked').value;
            if (!filePath) {
                showMessage('error', '请先选择一个视频文件。');
                return;
            }
            showProgressBar('正在分离视频...');
            document.getElementById('start-separation-btn').disabled = true;
            pywebview.api.api_separate_video(filePath, mode).then(response => {
                hideProgressBar();
                document.getElementById('start-separation-btn').disabled = false;
                if (response.status === 'success') {
                    showMessage('success', response.message || '视频分离成功！');
                    showOutputFiles(response.output_files);
                } else {
                    showMessage('error', '视频分离失败: ' + (response.message || '未知错误'));
                }
            }).catch(error => {
                hideProgressBar();
                document.getElementById('start-separation-btn').disabled = false;
                showMessage('error', '视频分离发生脚本错误: ' + error);
            });
        });
        
        // 开始音频切割
        document.getElementById('start-split-btn').addEventListener('click', () => {
            const filePath = document.getElementById('audio-file-path').value;
            const method = document.querySelector('input[name="split-method"]:checked').value;
            let value = 0;
            if (method === 'time') {
                value = document.getElementById('segment-time').value;
            } else {
                value = document.getElementById('segment-count').value;
            }
            if (!filePath) {
                showMessage('error', '请先选择一个音频文件。');
                return;
            }
            if (parseFloat(value) <= 0) {
                 showMessage('error', '切割值必须大于0。');
                 return;
            }
            showProgressBar('正在切割音频...');
            document.getElementById('start-split-btn').disabled = true;
            pywebview.api.api_split_audio(filePath, method, value).then(response => {
                hideProgressBar();
                document.getElementById('start-split-btn').disabled = false;
                if (response.status === 'success') {
                    showMessage('success', response.message || '音频切割成功！');
                    showOutputFiles(response.output_files);
                } else {
                    showMessage('error', '音频切割失败: ' + (response.message || '未知错误'));
                }
            }).catch(error => {
                hideProgressBar();
                document.getElementById('start-split-btn').disabled = false;
                showMessage('error', '音频切割发生脚本错误: ' + error);
            });
        });
        
        // 辅助函数
        function showMessage(type, text) {
            const msgElement = document.getElementById('message');
            msgElement.textContent = text;
            msgElement.className = 'message ' + type;
            msgElement.style.display = 'block'; 
        }
        
        function showProgressBar(text = '处理中...') {
            document.getElementById('progress-text').textContent = text;
            document.getElementById('progress-bar').style.width = '0%'; // Reset progress
            document.getElementById('progress-container').style.display = 'block';
            let width = 10;
            const interval = setInterval(function() {
                if (width >= 100) {
                    clearInterval(interval);
                } else {
                    width++;
                    document.getElementById('progress-bar').style.width = width + '%';
                }
            }, 50);
        }
        
        function hideProgressBar() {
            document.getElementById('progress-container').style.display = 'none';
            document.getElementById('progress-bar').style.width = '0%';
        }
        
        function showOutputFiles(files) {
            const outputListDiv = document.getElementById('output-list');
            const outputItemsDiv = document.getElementById('output-items');
            if (!files || files.length === 0) {
                outputItemsDiv.innerHTML = '没有输出文件。';
                outputListDiv.style.display = 'block';
                return;
            }
            outputItemsDiv.innerHTML = '';
            files.forEach(file => {
                const item = document.createElement('div');
                item.className = 'output-item';
                item.textContent = file;
                outputItemsDiv.appendChild(item);
            });
            outputListDiv.style.display = 'block';
        }

        // 在 pywebviewready 之后或者任何方便的地方添加这个事件监听器
        document.addEventListener('DOMContentLoaded', () => { // 或者放在 pywebviewready 内部
            const testBtn = document.getElementById('temp-test-py-api-btn');
            if(testBtn) {
                testBtn.addEventListener('click', () => {
                    console.log("Attempting to call pywebview.api.api_test_button");
                    if (pywebview && pywebview.api && typeof pywebview.api.api_test_button === 'function') {
                        pywebview.api.api_test_button().then(result => {
                            console.log("pywebview.api.api_test_button successful:", result);
                            alert("Python API test result: " + result);
                        }).catch(err => {
                            console.error("Error calling pywebview.api.api_test_button:", err);
                            alert("Error calling Python API: " + err);
                        });
                    } else {
                        console.error("pywebview.api.api_test_button is not a function or API not available.");
                        alert("pywebview.api.api_test_button is not available.");
                        // 打印出pywebview.api对象，看看里面有什么
                        if (pywebview && pywebview.api) {
                           console.log("Current pywebview.api object:", pywebview.api);
                           for (const key in pywebview.api) {
                               console.log(`pywebview.api.${key} : ${typeof pywebview.api[key]}`);
                           }
                        } else {
                           console.log("pywebview or pywebview.api is undefined.");
                        }
                    }
                });
            }
        });
    </script>
</body>
</html>